//
//  CharacterWriteView.swift
//  WCHBLEApp
//
//  Created by 娟华 胡 on 2021/3/24.
//

import UIKit
import RadioButton

class CharacterWriteView: UIView {
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var centerLayout: NSLayoutConstraint!
    
    @IBOutlet weak var aRadioButton: RadioButton!
    @IBOutlet weak var bRadioButton: RadioButton!
    @IBOutlet weak var sendLabel: UILabel!
    @IBOutlet weak var speedLabel: UILabel!
    @IBOutlet weak var sendButton: UIButton!
    
    public var sendData:((String)->Void)?
    public var clearWriteCallBack:(()->Void)?

    private var timer:Timer?
    private var count:Int = 0
    private var isHex:Bool = false
    private var updatedText:String?
    
    @IBAction func backAction(_ sender: Any) {
//        self.removeFromSuperview()
        self.textView.resignFirstResponder()
    }
    
    override func awakeFromNib() {
        self.textView.delegate = self
        self.textView.layer.borderWidth = 1.0
        self.textView.layer.borderColor = UIColor.blue.cgColor
        self.textView.layer.cornerRadius = 5.0
        aRadioButton.isSelected = true
        aRadioButton.groupButtons = [aRadioButton!, bRadioButton!]
    }
    
    @IBAction func shutAction(_ sender: Any) {
        self.removeFromSuperview()
        self.clearAction(sender)
    }
    
    @IBAction func hexAction(_ sender: Any) {
        let btn = sender as! UISwitch
        self.isHex = btn.isOn
        if (btn.isOn) {
            self.textView.text = self.textView.text.unicodeScalars.filter { $0.isASCII }
                                        .map{String(format: "%X ", $0.value) }
                                        .joined()
        }else {
            let str = self.textView.text ?? ""
            let array = str.split(separator: " ")
            self.textView.text = array.map {(String.init(data: Data.init(hex: String($0)), encoding: .utf8) ?? "")}.joined()
            
        }
    }
    
    @IBAction func sendAction(_ sender: Any) {
        if (self.textView.text.count == 0) {
            return
        }
        let btn = sender as! UIButton
        btn.isUserInteractionEnabled = false
        if (aRadioButton.isSelected) {
            self.sendButton.isSelected = false
            self.timer?.invalidate()
            self.timer = nil
            self.clearWriteCallBack?()
            self.send()
        }else {
            if (btn.isSelected) {
                self.timer?.invalidate()
                self.timer = nil
                
            }else {
                self.clearWriteCallBack?()
                self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(send), userInfo: nil, repeats: true)
                
            }
            btn.isSelected = !btn.isSelected
        }
        btn.isUserInteractionEnabled = true
    }
    
    @IBAction func clearAction(_ sender: Any) {
        self.textView.text = ""
        self.sendLabel.text = "发送计数：0 B"
        self.speedLabel.text =  "发送速度：0 B/S"
        self.timer?.invalidate()
        self.timer = nil
        self.sendButton.isSelected = false
        self.clearWriteCallBack?()
    }
    
    @objc func send() {
        if (self.isHex) {
            let str = self.textView.text ?? ""
            let array = str.split(separator: " ")
            let text = array.map {(String.init(data: Data.init(hex: String($0)), encoding: .utf8) ?? "")}.joined()
            self.sendData?(text)
        }else {
            self.sendData?(self.textView.text)
        }
        
    }
    
    public func showWriteSpeed(totalLength:Int64, time:TimeInterval) {
        self.sendLabel.text = "发送计数：\(totalLength) B"
    
        let speed = Double(totalLength) / time / 1024
        if (time > 0.001) {
            self.speedLabel.text = String.init(format: "发送速度：%0.1f KB/S", speed )
        }else {
            self.speedLabel.text = String.init(format: "发送速度：%0.1f B/S", Double(totalLength))
        }
    }
}

extension CharacterWriteView:UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        self.centerLayout.constant = -120
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        self.centerLayout.constant = 0
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let currentText = textView.text ?? ""
        
        guard let stringRange = Range(range, in: currentText) else { return false }
        
        var hexStr = text
        if (self.isHex) {
            hexStr = text.unicodeScalars.filter { $0.isASCII }
                         .map{String(format: "%X ", $0.value) }
                         .joined()
        }
        
        let updatedText = currentText.replacingCharacters(in: stringRange, with: hexStr)
        self.updatedText = updatedText
        
        return true
    }
    
    func textViewDidChange(_ textView: UITextView) {
        textView.text = updatedText
    }

}
